home *** CD-ROM | disk | FTP | other *** search
/ NetNews Offline 2 / NetNews Offline Volume 2.iso / news / comp / lang / c++-part2 / 18110 < prev    next >
Encoding:
Internet Message Format  |  1996-08-05  |  2.3 KB

  1. Path: user2.mnsinc.com!huang
  2. From: huang@mnsinc.com (Szu-Wen Huang)
  3. Newsgroups: comp.lang.c,comp.lang.c++
  4. Subject: Re: [Q] Multi-dimensional array problem!!!!!
  5. Followup-To: comp.lang.c,comp.lang.c++
  6. Date: 18 Apr 1996 23:15:48 GMT
  7. Organization: Monumental Network Systems
  8. Message-ID: <4l6if4$ebe@news1.mnsinc.com>
  9. References: <4l651f$p8v@oldfart.ecl.wustl.edu>
  10. NNTP-Posting-Host: user.mnsinc.com
  11. X-Newsreader: TIN [version 1.2 PL2]
  12.  
  13. Kyeong Soo Kim (kks@rgit.wustl.edu) wrote:
  14. [snip]
  15. : But, in my case, the dimension as well as the size of the
  16. : array is also an input parameter for the program. That is,
  17. : while I must treat 3x4 array in one situation, I must treat
  18. : 3x4x5 array in the other situation. One of the most simple
  19. : example is as follows:
  20. [snip]
  21.  
  22. Not that big a problem.  Here's how I'd solve it:  Allocate a
  23. one-dimensional memory chunk as usual that can hold the
  24. multi-dimensional array.  In English this would be:
  25.  
  26. x = malloc(size(dim1)*size(dim2)...sizeof(dimn));
  27.  
  28. Since the dimension is variable, the size might be computed in
  29. a loop like so:
  30.  
  31. for (i=0; i<NUMBER_OF_DIMENSIONS; i++)
  32.   totalsize *= SIZE_OF_DIMENSION[i];
  33. x = malloc(totalsize);
  34.  
  35. Now, having a big enough space to work on, we must now be able
  36. to address any element in the multi-dimensional array.  In general,
  37. element[subscript1][subscript2]...[subscriptn] can be stored in
  38. x[subscript1 * sum(size(dim2)..size(dimn)) +
  39.   subscript2 * sum(size(dim3)..size(dimn)) +
  40.   ...
  41.   subscript(n-1) * size(dimn) +
  42.   subscriptn]
  43.  
  44. *or*
  45.  
  46. x[subscript1 +
  47.   subscript2 * size(dim1) +
  48.   ...
  49.   subscriptn * sum(size(dim1)..size(dim(n-1)))]
  50.  
  51. The former is called row-major and the latter column-major.  There
  52. are various performance reasons why you want to use one over the
  53. other, but I'll leave that out unless you are really interested.
  54.  
  55. Coding the former in C might look like:
  56.  
  57. for (i=0; i<NUMBER_OF_DIMENSIONS; i++) {
  58.   for (j=i+1; j<NUMBER_OF_DIMENSIONS; j++)
  59.     rowsize += SIZE_OF_DIMENSION[j];
  60.   index += SUBSCRIPT[i] * rowsize;
  61. }
  62. x[index] is the element we look for
  63.  
  64. Okay, I hope this solves your problem.  Note that the C code I
  65. posted won't run as is because they are only meant to show what
  66. the actual code might look like and are missing initializations
  67. and range checks.  You should be able to produce working code
  68. from here on.  Hope this helps.
  69.